﻿#region License
/* Copyright (C) 2009 Tim Coulter
 * 
 * This file is part of ExtremeML.
 * 
 * ExtremeML is free software: you can redistribute
 * it and/or modify it under the terms of the GNU General Public
 * License, as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 * 
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty
 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See
 * the GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see http://www.gnu.org/licenses/.
*/
#endregion

using System;
using ExtremeML.Core;

namespace ExtremeML.Spreadsheet.Address
{
	/// <summary>
	/// Represents the addressing for a contiguous set of rows.
	/// </summary>
	public class RowSpan : IAddressDependency, IWrapper, IComparable<RowSpan>
	{
		#region Housekeeping

		/// <summary>
		/// Initializes a new instance of the <see cref="RowSpan"/> class.
		/// </summary>
		internal RowSpan()
		{
		}

		/// <summary>
		/// Initializes a new instance of the <see cref="RowSpan"/> class.
		/// </summary>
		/// <param name="begin">A nullable <see cref="int"/> that specifies the first row in this span.</param>
		/// <param name="end">A nullable <see cref="int"/> that specifies the last row in this span.</param>
		internal RowSpan(
			int? begin,
			int? end)
			: this (begin, end, false, false)
		{
		}

		/// <summary>
		/// Initializes a new instance of the <see cref="RowSpan"/> class.
		/// </summary>
		/// <param name="begin">A nullable <see cref="int"/> that specifies the first row in this span.</param>
		/// <param name="end">A nullable <see cref="int"/> that specifies the last row in this span.</param>
		/// <param name="beginAbsolute">A value that indicates whether the begin row coordinate is absolute.</param>
		/// <param name="endAbsolute">A value that indicates whether the end row coordinate is absolute.</param>
		internal RowSpan(
			int? begin,
			int? end,
			bool beginAbsolute,
			bool endAbsolute)
		{
			if (begin < 0) throw new ArgumentOutOfRangeException("begin");
			if (end < 0) throw new ArgumentOutOfRangeException("end");

			Begin = begin;
			End = end;
			BeginAbsolute = beginAbsolute;
			EndAbsolute = endAbsolute;
		}

		#endregion
		#region Properties

		/// <summary>
		/// Gets the zero-based index of the first row in the span.
		/// </summary>
		public int? Begin { get; internal set; }

		/// <summary>
		/// Gets the zero-based index of the last row in the span.
		/// </summary>
		public int? End { get; internal set; }

		/// <summary>
		/// Gets whether the begin row coordinate is absolute.
		/// </summary>
		public bool? BeginAbsolute { get; internal set; }

		/// <summary>
		/// Gets whether the end row coordinate is absolute.
		/// </summary>
		public bool? EndAbsolute { get; internal set; }

		/// <summary>
		/// Gets the number of rows in the span.
		/// </summary>
		public int? Height
		{
			get { return End - Begin + 1; }
		}

		/// <summary>
		/// Gets the pair of row numbers that represent the upper and lower boundaries of this span.
		/// </summary>
		public string Spans
		{
			get
			{
				if (!IsPopulated()) return null;

				return (BeginAbsolute.Value ? "$" : string.Empty) +
					(Begin + 1) +
					":" +
					(EndAbsolute.Value ? "$" : string.Empty) +
					(End + 1);
			}
		}

		#endregion
		#region Static Methods


		#endregion
		#region Interface Implementation
		#region IAddressDependency

		/// <summary>
		/// Accepts notification that the specified number of empty
		/// rows have been inserted before the specified row index.
		/// </summary>
		/// <param name="rowIndex">The zero-based index of the row that follows the insertion point.</param>
		/// <param name="rowCount">The number of rows inserted.</param>
		public void NotifyRowInsertion(
			int rowIndex,
			int rowCount)
		{
			if (rowIndex < 0) throw new ArgumentOutOfRangeException("rowIndex");
			if (rowCount < 0) throw new ArgumentOutOfRangeException("rowCount");

			if (IsPopulated())
			{
				var begin = Begin.Value;
				var end = End.Value;

				if (begin >= rowIndex)
				{
					// Shift
					Begin += rowCount;
				}
				else if (end >= rowIndex)
				{
					// Resize
					End += rowCount;

					if (RowsInserted != null)
					{
						RowsInserted(this, new RangeResizeEventArgs(rowIndex - begin, rowCount));
					}
				}
			}
		}

		/// <summary>
		/// Accepts notification that the specified number of rows
		/// have been deleted, starting at the specified row index.
		/// </summary>
		/// <param name="rowIndex">The zero-based index of the first row deleted.</param>
		/// <param name="rowCount">The number of rows deleted.</param>
		public void NotifyRowDeletion(
			int rowIndex,
			int rowCount)
		{
			if (rowIndex < 0) throw new ArgumentOutOfRangeException("rowIndex");
			if (rowCount < 0) throw new ArgumentOutOfRangeException("rowCount");

			if (IsPopulated())
			{
				// For an explanation of the logic applied here, refer to
				// the "Excel Observations" section of the developer guide.
				var begin = Begin.Value;
				var end = End.Value;

				if (begin >= rowIndex + rowCount)
				{
					// Shift
					Begin -= rowCount;
					End -= rowCount;
				}
				else if (begin >= rowIndex && end >= rowIndex + rowCount)
				{
					// Crop upper
					End -= rowCount;
					rowCount = rowIndex + rowCount - begin;
					Begin = rowIndex;

					if (RowsDeleted != null)
					{
						RowsDeleted(this, new RangeResizeEventArgs(0, rowCount));
					}
				}
				else if (begin < rowIndex && end >= rowIndex && end < rowIndex + rowCount)
				{
					// Crop lower
					rowCount = end - rowIndex + 1;
					End = rowIndex - 1;

					if (RowsDeleted != null)
					{
						RowsDeleted(this, new RangeResizeEventArgs(rowIndex - begin, rowCount));
					}
				}
				else if (begin >= rowIndex && end < rowIndex + rowCount)
				{
					// Delete
					if (SpanDeleted != null)
					{
						SpanDeleted(this, EventArgs.Empty);
					}
				}
				else if (begin < rowIndex && end >= rowIndex + rowCount)
				{
					// Resize
					End -= rowCount;

					if (RowsDeleted != null)
					{
						RowsDeleted(this, new RangeResizeEventArgs(rowIndex - begin, rowCount));
					}
				}
			}
		}

		/// <summary>
		/// Accepts notification that the specified number of empty
		/// columns have been inserted before the specified column index.
		/// </summary>
		/// <param name="columnIndex">The zero-based index of the column that follows the insertion point.</param>
		/// <param name="columnCount">The number of columns inserted.</param>
		public void NotifyColumnInsertion(
			int columnIndex,
			int columnCount)
		{
			// Column insertion does not affect row spans.
		}

		/// <summary>
		/// Accepts notification that the specified number of columns
		/// have been deleted, starting at the specified column index.
		/// </summary>
		/// <param name="columnIndex">The zero-based index of the column that follows the insertion point.</param>
		/// <param name="columnCount">The number of columns inserted.</param>
		public void NotifyColumnDeletion(
			int columnIndex,
			int columnCount)
		{
			// Column deletion does not affect row spans.
		}

		#endregion
		#region IWrapper

		/// <summary>
		/// Returns a value that indicates whether this instance wraps content that should be saved to the document.
		/// </summary>
		public bool IsPopulated()
		{
			return Begin.HasValue && End.HasValue && BeginAbsolute.HasValue && EndAbsolute.HasValue;
		}

		/// <summary>
		/// Establishes relationships with other package content objects.
		/// </summary>
		public void Activate()
		{
			// This class requires no activation.		
		}

		/// <summary>
		/// Safely terminates relationships with other package content objects.
		/// </summary>
		public void Deactivate()
		{
			// This class requires no deactivation.		
		}

		#endregion
		#region IComparable<T>

		/// <summary>
		/// Implements interface <see cref="IComparable{T}"/>
		/// </summary>
		/// <param name="other">A <see cref="RowSpan"/> to compare with this instance.</param>
		/// <returns>A 32-bit signed integer that indicates the relative order of the objects being compared.</returns>
		public int CompareTo(
			RowSpan other)
		{
			if (Begin > other.Begin)
			{
				// This instance is greater than other 
				return 1;
			}
			else if (Begin < other.Begin)
			{
				// This instance is less than other 
				return -1;
			}
			else
			{
				// The two instances are equal
				return 0;
			}
		}

		#endregion
		#endregion
		#region Overrides

		/// <summary>
		/// Overrides the base class to return the value of the <see cref="Spans"/> property.
		/// </summary>
		/// <returns>A <see cref="string"/> that represents the value of this instance.</returns>
		/// <remarks>For compatibility with Excel formula syntax, this value is enclosed in parentheses.</remarks>
		public override string ToString()
		{
			return string.Format("({0})", Spans);
		}

		/// <summary>
		/// Overrides the equality operator to compare the values of two <see cref="RowSpan"/> instances.
		/// </summary>
		/// <param name="a">A <see cref="RowSpan"/> instance to compare.</param>
		/// <param name="b">A <see cref="RowSpan"/> instance to compare.</param>
		/// <returns>A value that indicates whether the passed instances are equal.</returns>
		public static bool operator ==(
			RowSpan a,
			RowSpan b)
		{
			return
				a.IsPopulated() &&
				b.IsPopulated() &&
				a.Begin == b.Begin &&
				a.BeginAbsolute == b.BeginAbsolute &&
				a.End == b.End &&
				a.EndAbsolute == b.EndAbsolute;
		}

		/// <summary>
		/// Overrides the inequality operator to compare the values of two <see cref="RowSpan"/> instances.
		/// </summary>
		/// <param name="a">A <see cref="RowSpan"/> instance to compare.</param>
		/// <param name="b">A <see cref="RowSpan"/> instance to compare.</param>
		/// <returns>A value that indicates whether the passed instances are not equal.</returns>
		public static bool operator !=(
			RowSpan a,
			RowSpan b)
		{
			return !(a == b);
		}

		#endregion
		#region Events

		/// <summary>
		/// Occurs when the row insertion changes the height of this span.
		/// </summary>
		internal event RangeResizeEventHandler RowsInserted;

		/// <summary>
		/// Occurs when the row deletion changes the height of this span.
		/// </summary>
		internal event RangeResizeEventHandler RowsDeleted;

		/// <summary>
		/// Occurs when the this span is deleted by a worksheet row deletion operation.
		/// </summary>
		internal event EventHandler SpanDeleted;

		#endregion
	}
}
